package com.housekeeping.service.impl;

import com.housekeeping.dao.UserDAO;
import com.housekeeping.dao.impl.UserDAOImpl;
import com.housekeeping.model.User;
import com.housekeeping.service.UserService;

import java.util.Date;
import java.util.List;

/**
 * 用户服务实现类
 */
public class UserServiceImpl implements UserService {
    
    private UserDAO userDAO = new UserDAOImpl();

    @Override
    public User login(String username, String password) {
        if (username == null || password == null) {
            return null;
        }
        return userDAO.findByUsernameAndPassword(username, password);
    }

    @Override
    public boolean register(User user) {
        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            return false;
        }
        
        
        if (isUsernameExists(user.getUsername())) {
            return false;
        }
        
        
        if (user.getUserType() == null) {
            user.setUserType(2); 
        }
        if (user.getStatus() == null) {
            user.setStatus(1); 
        }
        user.setCreateTime(new Date());
        
        return userDAO.insert(user) > 0;
    }

    @Override
    public boolean isUsernameExists(String username) {
        return userDAO.findByUsername(username) != null;
    }

    @Override
    public User getUserById(Integer userId) {
        return userDAO.findById(userId);
    }

    @Override
    public List<User> getAllUsers() {
        return userDAO.findAll();
    }

    @Override
    public List<User> getCustomers() {
        return userDAO.findByUserType(2); 
    }

    @Override
    public List<User> getStaff() {
        return userDAO.findByUserType(3); 
    }

    @Override
    public boolean updateUser(User user) {
        if (user == null || user.getUserId() == null) {
            return false;
        }
        user.setUpdateTime(new Date());
        return userDAO.update(user) > 0;
    }

    @Override
    public boolean deleteUser(Integer userId) {
        return userDAO.delete(userId) > 0;
    }

    @Override
    public boolean updateUserStatus(Integer userId, Integer status) {
        User user = userDAO.findById(userId);
        if (user != null) {
            user.setStatus(status);
            user.setUpdateTime(new Date());
            return userDAO.update(user) > 0;
        }
        return false;
    }

    @Override
    public List<User> getUsersByType(Integer userType) {
        return userDAO.findByUserType(userType);
    }

    @Override
    public long getUserCount() {
        return userDAO.count();
    }
} 